package com.cuitrip.business.home.travel;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.recommend.model.HomeCardType;
import com.cuitrip.business.home.travel.model.FilterExp;
import com.cuitrip.business.home.travel.model.FilterInfo;
import com.cuitrip.business.home.travel.model.SelectInfo;
import com.cuitrip.business.home.travel.ui.FilterAdapter;
import com.cuitrip.business.home.travel.ui.FilterInfoViewHolder;
import com.cuitrip.business.home.trip.model.Facet;
import com.cuitrip.business.search.SearchActivity;
import com.cuitrip.service.R;
import com.lab.app.BaseActivity;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ArrayUtil;
import com.lab.utils.LogHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * <p/>
 * Created by sheena on 15/11/4.
 */
public class TravelTripListSelectFragment extends CustomUiFragment implements IProxyCallback {


    @Bind(android.R.id.list)
    RecyclerView mRecyclerView;

    private List<FilterInfo> mFilterInfoList = new ArrayList<>();
    private SelectInfo selectInfo;

    private ApiProxy mApiProxy = new ApiProxy(this);
    //首页卡片类型
    private int type;

    public TravelTripListFragment.SelectCallback mSelectCallback;
    private String searchTag;


    public void setSelectCallback(TravelTripListFragment.SelectCallback mSelectCallback) {
        this.mSelectCallback = mSelectCallback;
    }

    public TravelTripListSelectFragment() {
    }

    public static TravelTripListSelectFragment newInstance(SelectInfo selectInfo) {
        TravelTripListSelectFragment selectFragment = new TravelTripListSelectFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("selectInfo", selectInfo);
        selectFragment.setArguments(bundle);
        return selectFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState, R.layout.fragment_trip_category_filter);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            searchTag = getArguments().getString(SearchActivity.TAG);
            this.selectInfo = (SelectInfo) getArguments().getSerializable("selectInfo");
            String sourceUri = getArguments().getString(BaseActivity.SOURCE_URI_KEY);
            if (!TextUtils.isEmpty(sourceUri)) {
                Uri uri = Uri.parse(sourceUri);
                String typeParameter = uri.getQueryParameter("type");
                try {
                    type = Integer.valueOf(typeParameter);
                } catch (Exception e) {
                    LogHelper.e("TravelTripListSelectFragment", "NumberFormatException ", e);
                }
            } else {
                type = -1;
                LogHelper.e("TravelTripListSelectFragment", "type is not found ");
            }
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this, getView());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getHostActivity(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(new FilterAdapter(mFilterInfoList));
    }

    @Override
    public void initData() {
        TripBusiness.getSearchNaviParm(mApiProxy);
    }



    private SelectInfo bindModel() {
        return selectInfo;
    }


    @Override
    public void onTopbarLeftPress() {
        getHostActivity().onBackPressed();
    }

    @Override
    public void onTopbarRightPress() {
        bindFilterInfo();
        selectInfo.setFilterInfoList(mFilterInfoList);
        if (mSelectCallback != null) {
            SelectInfo selectInfo = bindModel();
            if (selectInfo != null) {
                mSelectCallback.onResultBack(selectInfo);
            }
        }
        getHostActivity().onBackPressed();
    }

    private void bindFilterInfo() {
        int size = mRecyclerView.getAdapter().getItemCount();
        for (int i = 0; i < size; i++) {
            FilterInfo filterInfo = mFilterInfoList.get(i);
            RecyclerView.ViewHolder viewHolder = mRecyclerView.findViewHolderForAdapterPosition(i);
            if (viewHolder instanceof FilterInfoViewHolder) {
                FilterInfoViewHolder filterInfoViewHolder = (FilterInfoViewHolder) viewHolder;
                ListView listView = filterInfoViewHolder.mFilterListView;
                int listCount = listView.getAdapter().getCount();
                for (int j = 0; j < listCount; j++) {
                    boolean isChecked = listView.isItemChecked(j);
                    filterInfo.getValues().get(j).setSelected(isChecked);
                }

            }

        }
    }


    private void inflateList(List<FilterInfo> filterInfoList) {
        //上一次选择的筛选值
        List<FilterInfo> filterInfoListPre = selectInfo.getFilterInfoList();
        List<FilterInfo.ValueInfo> selectedValueList=new ArrayList<>();
        for (FilterInfo filterInfoPre : filterInfoListPre){
            selectedValueList.addAll(filterInfoPre.getSelectedValueList());

        }
        mFilterInfoList.clear();
        //本次请求到的所有筛选值
        for (FilterInfo filterInfo : filterInfoList) {
            /**
             * 如果是专题列表或是搜索进入，主题不显示
             */
            if ((type == HomeCardType.SUBJECT_SEARCH.value || SearchActivity.TAG.equals(searchTag)) && FilterInfo.CATEGORY_KEY.equals(filterInfo.getSearchKey())) {
                continue;
            }
            Facet facet = selectInfo.retrieveFacetFrom(filterInfo.searchKey);
            ArrayList<FilterInfo.ValueInfo> values = filterInfo.getValues();
            if(!ArrayUtil.isNullOrEmpty(values)){
                List<String> validCateKeyList = null;
                if (facet != null){
                    validCateKeyList = facet.getValidCateItemKeyList();
                }
                for (FilterInfo.ValueInfo valueInfo:values){
                    if (validCateKeyList != null && !validCateKeyList.contains(valueInfo.getV())){
                        valueInfo.setShow(false);
                    }
                    if (selectedValueList.contains(valueInfo)){
                        valueInfo.setSelected(true);
                    }
                }
            }
            mFilterInfoList.add(filterInfo);
        }
        mRecyclerView.getAdapter().notifyDataSetChanged();
    }


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_SEARCH_NAVIPARM.equals(response.getApiName())) {
            if (response != null && response.code == CtResponseCode.RESULT_OK) {
                if (response.result instanceof FilterExp) {
                    FilterExp filterExp = (FilterExp) response.result;
                    ArrayList<FilterInfo> list = filterExp.getFilterExp();
                    inflateList(list);
                    return false;

                }
            }
        }

        return false;
    }


    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mTopbarMiddleAreaName = getString(R.string.filter);
        customUiConfig.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        customUiConfig.mTopbarRightAreaName = getString(R.string.operation_ok_1);
        return customUiConfig;
    }


}
